<?php
/**
 *
 *
 *
 */
class Yz_Form_Element_UploadImage
    extends Yz_Form_Element_Abstract
    implements Yz_Form_Element_Interface
{

    protected $name;
    protected $value = 0;
    protected $filename = "";
    protected $filenameField = "uploadFileName";


    /**
     *  @param array $values
     *  @return chainable
     */
    public function assignValueFromArray(array $values)
    {
        $name = $this->name;
        if (array_key_exists($name, $values)) {
            $filename = $this->filenameField;
            if (array_key_exists($filename, $values)) {
                $this->setValue($values[$name]);
                $this->filename = $values[$filename];
            } else {
                debug("Key {$filename} is missing, value not set");
            }
        }
        return $this;
    }

    /**
     *
     */
    public function render(Yz_Template_Interface $parentTemplate)
    {
        $template = $parentTemplate->createTemplate('UploadDialog', 'Uploads');

        $template->elName       = $this->name;
        $template->elValue      = $this->value;
        $template->action       = $this->getUploadAction();
        $template->filename     = $this->filename;
        $template->cssClass     = $this->getCSSClass();
        $template->uploadPath   = $this->getUploadPath();

        return $parentTemplate->renderTemplate($template);

    }


    /**
     *  @return this
     *  @throw Yz_Form_Element_Exception
     */
    public function parse(Yz_Hash $values)
    {
        $elName = $this->name;
        debug("Element '$elName'");
        $value = $values[$elName];
        $value = Yz_Int::valueOf($value);
        if (null === $value) {
            throw new Yz_Form_Element_Exception("Invalid value for element {$elName} (must be an integer number)");
        }
        $this->value = $value;
        return $this;
    }


    protected function getUploadAction()
    {
        return $this->element->uploadAction;
    }

    protected function getUploadPath()
    {
        return $this->element->uploadPath;
    }

}
